<template>
  <view class="viewport">
    <view class="content form">
      <uni-forms ref="formRef" :model="formData" :rules="rules">
        <uni-forms-item label="收货人" name="receiver" class="form-item">
          <uni-easyinput v-model="formData.receiver" type="text" placeholder="请填写收货人" />
        </uni-forms-item>
        <uni-forms-item label="手机号码" name="contact" class="form-item">
          <uni-easyinput v-model="formData.contact" type="text" placeholder="请填写手机号码" />
        </uni-forms-item>
        <uni-forms-item label="所在地区" name="fullLocation" class="form-item">
          <picker
            class="picker"
            mode="region"
            @change="onLocationChange"
            :value="formData.fullLocation.split(' ')"
            style="width: 100%"
          >
            <view v-if="formData.fullLocation" class="value">{{ formData.fullLocation }}</view>
            <view v-else class="placeholder">请选择省/市/区</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="详细地址" name="address" class="form-item">
          <uni-easyinput v-model="formData.address" type="text" placeholder="街道、楼牌号等信息" />
        </uni-forms-item>
        <uni-forms-item label="设为默认地址" name="isDefault" class="form-item switch-item">
          <switch :checked="formData.isDefault === 1" @change="onIsDefaultChange" />
        </uni-forms-item>
      </uni-forms>
    </view>
    <button class="btn" @tap="onSubmit">保存并使用</button>
  </view>
</template>

<script lang="ts" setup>
import type { TAddressResult } from '@/types/address'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import _ from 'lodash'
import Api from '@/services/index'

const formRef = ref<UniHelper.UniFormsInstance>()

const formData = ref<TAddressResult>({
  id: '',
  receiver: '', // 收货人
  contact: '', // 联系方式
  fullLocation: '', // 省市区(前端展示)
  provinceCode: '', // 省份编码(后端参数)
  cityCode: '', // 城市编码(后端参数)
  countyCode: '', // 区/县编码(后端参数)
  address: '', // 详细地址
  isDefault: 0, // 默认地址，1为是，0为否
})

const rules: UniHelper.UniFormsRules = {
  receiver: {
    rules: [{ required: true, errorMessage: '请填写收货人' }],
  },
  contact: {
    rules: [
      { required: true, errorMessage: '请填写联系方式' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
    ],
  },
  fullLocation: {
    rules: [{ required: true, errorMessage: '请选择省市区' }],
  },
  address: {
    rules: [{ required: true, errorMessage: '请输入详细地址' }],
  },
}

onLoad(async (options) => {
  if (options?.id) {
    uni.setNavigationBarTitle({
      title: '修改地址',
    })
    formData.value.id = options.id
    const res = await Api.LoginAPI.getAddressDetail(options.id)
    formData.value = { ...res.result }
  }
})

const onSubmit = async () => {
  // formRef.value?.validate?.()!.then((res) => {
  //   console.log(res, 'res')
  // })
  try {
    await formRef.value?.validate?.()
    const params = _.omit(formData.value, ['fullLocation', 'id'])
    if (formData.value.id) {
      // console.log(id)
      // 编辑
      const res = await Api.LoginAPI.updateAddressById(formData.value.id, params)
      if (res.code === '1') {
        uni.showToast({
          icon: 'success',
          title: '更新成功',
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      }
    } else {
      // 新增

      const res = await Api.LoginAPI.addAddress(params)
      if (res.code === '1') {
        uni.showToast({
          icon: 'success',
          title: '新增成功',
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      }
    }
  } catch (e) {
    console.log(e, 'e')
    uni.showToast({
      icon: 'error',
      title: '出错啦！！',
    })
  }
}

const onLocationChange: UniHelper.RegionPickerOnChange = (ev) => {
  formData.value.fullLocation = ev.detail.value.join(' ')
  formData.value.provinceCode = ev.detail.code![0]
  formData.value.cityCode = ev.detail.code![1]
  formData.value.countyCode = ev.detail.code![2]
}
const onIsDefaultChange: UniHelper.SwitchOnChange = (ev) => {
  formData.value.isDefault = ev.detail.value ? 1 : 0
}
</script>

<style lang="scss" scoped>
.viewport {
  height: 100vh;
  background-color: #f4f4f4;
  padding: 20rpx 20rpx 0 20rpx;

  .content {
    background-color: #fff;
    padding: 0 20rpx;

    .placeholder {
      width: 100%;
      line-height: 50rpx;
      color: #999;
      font-size: 24rpx;
      padding-left: 20rpx;
    }

    .value {
      padding-left: 20rpx;
    }
  }

  .btn {
    padding: 0;
    margin: 0;
    margin-top: 30rpx;
    line-height: 2;
    font-size: 32rpx;
    color: #fff;
    border-radius: 50rpx;
    background-color: #27ba9b;
  }
}

:deep {
  .form-item,
  .uni-forms-item {
    display: flex;
    width: 100%;
    border-bottom: 1px solid #e5e5e5;
    margin: 0;
    padding: 20rpx 0;
    .uni-forms-item__label {
      width: 30% !important;
      height: 50rpx;
      line-height: 50rpx;
    }

    .uni-forms-item__content {
      display: flex;
      line-height: 50rpx;
      height: 50rpx;
      justify-content: flex-end;
      .uni-easyinput__content {
        height: 50rpx;
        border: none !important;
        border-radius: 0;
      }
      switch {
        line-height: 50rpx;
        transform: scale(0.6);
      }
      .uni-forms-item__error {
        top: 40rpx;
        left: 20rpx;
      }
    }
  }
}
</style>
